package org.baicaixiaozhan.learn.guava.collect;

import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import org.baicaixiaozhan.learn.guava.domain.User;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * DESC: {@link Multimap} 示例
 *
 * @author : baicaixiaozhan
 * @since 2020/11/13
 */
public class MultimapDemo {

    public static void main(String[] args) {

        // JDK
        // as a collection of mappings from single keys to single values
        /*
            a -> 1
            a -> 2
            a -> 4
            b -> 3
            c -> 5
         */
        similarMultimapInJava();

        // Guava
        // as a mapping from unique keys to collections of values
        /*
            a -> [1, 2, 4]
            b -> [3]
            c -> [5]
         */
        multimapInGuava();
    }

    public static void similarMultimapInJava() {
        IdentityHashMap<String, User> map = new IdentityHashMap<>();
        map.put(new String("A"), new User(1, "张三"));
        map.put(new String("A"), new User(5, "李四"));
        map.put(new String("C"), new User(8, "王五"));
        map.put(new String("A"), new User(3, "赵六"));
        map.put(new String("B"), new User(9, "田七"));

        System.out.println("build by IdentityHashMap : " + map.toString());
    }

    public static void multimapInGuava() {
        multimapByTreeKeys();
        multimapByHashKeys();
    }

    public static void multimapByTreeKeys() {
        Multimap<String, User> listMultimap = MultimapBuilder.treeKeys().arrayListValues().build();
        multimapConsumer.accept(listMultimap);
    }
    public static void multimapByHashKeys() {
        Multimap<String, User> listMultimap = MultimapBuilder.hashKeys().arrayListValues().build();
        multimapConsumer.accept(listMultimap);
    }

    static Consumer<Multimap<String, User>> multimapConsumer = listMultimap -> {
        listMultimap.put("A", new User(1, "张三"));
        listMultimap.put("A", new User(5, "李四"));
        listMultimap.put("C", new User(8, "王五"));
        listMultimap.put("A", new User(3, "赵六"));
        listMultimap.put("B", new User(9, "田七"));

        System.out.println("build by Multimap : " + listMultimap.toString());
        listMultimap.get("A").forEach(System.out::println);
    };
}
